﻿package net.nicoptere.media.video.tracker3d 
{
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	/**
	 * @author Nicolas Barradeau 
	 */
	public class Sequence extends Sprite
	{
		
		private var interval:int;
		private var bmp:Bitmap;
		
		private var _frames:Array = [];
		public function get frames():Array  { return _frames; }
		
		private var _currentFrame:uint = 0;
		public function get currentFrame():uint  { return _currentFrame; }
		
		
		public function Sequence() 
		{
			bmp = Bitmap( addChild( new Bitmap( null, "auto", true ) ) );
			addChild( bmp );
		}
		
		public function addFrame( frame:Frame ):void 
		{
			_frames.push( frame );
		}
		
		public function play():void 
		{
			clearInterval( interval );
			interval = setInterval( nextFrame, ( 1000 / Tracker3D.FPS ) );
		}
		public function stop():void 
		{
			clearInterval( interval );
		}
		public function nextFrame():void 
		{
			var f:int = _currentFrame + 1;
			updateBitmap( f );
		}
		public function prevFrame():void 
		{
			var f:int = _currentFrame - 1;
			updateBitmap( f );
		}
		public function gotoAndPlay( frame:uint ):void 
		{
			updateBitmap( frame );
		}
		
		public function gotoAndStop( frame:uint ):void 
		{
			updateBitmap( frame );
		}
		
		protected function updateBitmap( frame:int ):void
		{
			
			if ( frames.length <= 0 ) return;
			
			if ( frame > frames.length - 1 ) frame = frames.length - 1;
			if ( frame < 0 ) frame = 0;
			
			_currentFrame = frame;
			
			var f:Frame = frames[ _currentFrame ];
			bmp.bitmapData = f;
			bmp.x = f.position.x;
			bmp.y = f.position.y;
			
		}
	}

}